<template>
  <div class="app-container">
    <audio controls ref="audioElement" hidden="hidden">
      <source src="@/audio/xm2779.mp3" />
    </audio>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>布防任务列表</span>
        <el-button style="float: right;" type="primary" @click="handleCreate">创建任务</el-button>
      </div>
      <div class="filter-container">
        <el-form :inline="true" :model="pageHelper" class="demo-form-inline">
          <el-form-item label="布控任务名称">
            <el-input v-model="pageHelper.controlName" placeholder="布防名称"></el-input>
          </el-form-item>
          <el-form-item label="布控状态">
            <el-select v-model="pageHelper.controlStatus" placeholder="请选择布防状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="未开始" value="0"></el-option>
              <el-option label="执行中" value="1"></el-option>
              <el-option label="已暂停" value="2"></el-option>
              <el-option label="已结束" value="3"></el-option>
              <el-option label="已撤销" value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="布控时间">
            <el-date-picker
              v-model="pageHelper.defenseTime"
              type="datetime"
              placeholder="选择布控时间"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getData">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <template>
      <div class="card-container">
        <!-- 使用v-for遍历tableData数组 -->
        <div class="card" v-for="(item, index) in tableData" :key="item.id">
          <div class="card-header">
            <span>序号: {{ index + 1 }}</span>
          </div>
          <div class="card-content">
            <!-- 根据需要显示数据，这里假设每行数据都有id, taskName, status等属性 -->
            <div class="card-info">
              <span>布防名称: {{ item.controlName }}</span>
            </div>
            <div class="card-info">
           布防状态:<dict-tag :options="dict.type.defense_statu" :value="item.defenseStatus"></dict-tag>
            </div>
            <div class="card-info">
              <span>布防人: {{ item.publisher }}</span>
            </div>
            <div class="card-info">
              <span>开始时间: {{ formattedStartDate(item.startTime) }}</span>
            </div>
            <div class="card-info">
              <span>结束时间: {{ formattedStartDate(item.endTime) }}</span>
            </div>
            <div class="card-info">
              <span>布控车牌:</span>
              <img :src="getImageSrc(item.pic)" alt="布控对象图片" />
            </div>
          </div>
          <div class="card-footer">
            <!-- 添加操作按钮，绑定点击事件 -->
            <el-button size="mini" @click="dialogupd = true,handleEdits(index, item)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDeletes(index, item)">撤控</el-button>
          </div>
        </div>
      </div>
      </template>

    </el-card>
    <el-dialog title="新增人员布防" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="布防名称" :label-width="formLabelWidth">
          <el-input v-model="form.defenseName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防开始时间" :label-width="formLabelWidth">
          <el-input v-model="form.defenseStartDate" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防结束时间" :label-width="formLabelWidth">
          <el-input v-model="form.defenseEndDate" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防对象" :label-width="formLabelWidth">
          <el-input v-model="form.defensePerson" autocomplete="off"></el-input>
          <el-upload
            action="/dev-api/base-distribution/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="布防人姓名" :label-width="formLabelWidth">
          <el-input v-model="form.defensePersonName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>
    <!-- Form -->
    <el-dialog title="布控详情" :visible.sync="dialogupd">
      <el-form :model="formupd">
        <el-form-item label="序号" :label-width="formLabelWidth">
          <el-input v-model="formupd.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防名称" :label-width="formLabelWidth">
          <el-input v-model="formupd.defenseName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防状态" :label-width="formLabelWidth">
          <el-select v-model="formupd.defenseStatus" placeholder="请选择布防状态">
            <el-option label="未开始" value="0"></el-option>
            <el-option label="执行中" value="1"></el-option>
            <el-option label="已暂停" value="2"></el-option>
            <el-option label="已结束" value="3"></el-option>
            <el-option label="已撤销" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="布防人" :label-width="formLabelWidth">
          <el-input v-model="formupd.defenseCreator" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="布防开始时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="formupd.defenseStartDate"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="12:00:00"
            arrow-control>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="布防结束时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="formupd.defenseEndDate"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="12:00:00"
            arrow-control>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="布防对象" :label-width="formLabelWidth">
          <img :src="formupd.defensePerson"  />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogupd = false">取 消</el-button>
        <el-button type="primary" @click="upd">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {adddefense, carlist, findDefense, upddefence, updstatu} from "../../../api/IC/gen";

export default {
  dicts: ['defense_statu'],
  name: "index.vue",
  data() {
    return {
      dialogupd:false,
      formupd:{},
      pageHelper: {
        pageNum:1,
        pageSize:10,
        licenseNumber:'',
        controlStatus:'',
      },
      formInline:{},
      socket: null,
      timeout: 10 * 1000, // 45秒一次心跳
      timeoutObj: null, // 心跳心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时
      lockReconnect: false, // 防止
      websocket: null,
      form:{
        defensePerson:'',
        defenseCreator:'徐立扬'
      },
      dialogFormVisible:false,
      tableData: [
      ],
      currentPage: 1,
      pageSize: 10,
      total: 50,
      listQuery: {
        keyword: '',
        status: '',
        dateRange: []
      },
      item: {
        defensePerson:'',
        defenseStartDate:new Date()
      },
      formLabelWidth: '120px',

    };
  },
  methods: {
    handleDeletes(index,item){
      updstatu(item.id).then(res=>{
        if(res.code==200)
        {
          this.$message.success('撤销成功');
          this.getData();
        }
        else {
          this.$message.error("撤销失败");
          this.getData();
        }
      })
    },
    upd(){
      upddefence(this.formupd).then(res=>{
        if(res.code==200){
          this.$message.success('修改成功');
          this.dialogupd=false;
          this.getData();
        }else{
          this.$message.error(res.message);
        }
      })
    },
    handleEdits(index,item)
    {
       this.formupd=Object.assign({},item);
       this.dialogupd=true;
    },
    formattedStartDate(dateTime) {
      // 假设dateTime是一个字符串
      return dateTime.replace('T', ' ');
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    getImageSrc(base64String) {

      // 检查字符串是否以正确的格式开始
      if (base64String.startsWith('data:image/')) {
        return base64String;
      }

      // 如果不是以 'data:image/' 开头，返回默认图片
      return 'default-image-url.jpg';
    },
    getData()
    {
      carlist(this.pageHelper).then(res=>{
        alert(JSON.stringify(res))
        this.tableData=res.data.list;
      })
    },
    handleCreate() {
      this.dialogFormVisible=true;
      console.log("创建任务");
    },
    handleEdit(index, row) {
      console.log("编辑任务", index2, row);
    },
    handleDelete(index, row) {
      console.log("删除任务", index2, row);
    },
    handleFilter() {

      console.log("搜索", this.listQuery);
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },

    handleSuccess(response, file, fileList)
    {
      const response2 =response.substring(56);
      const response3=response2.substring(0,11)+"jpeg"+response2.substring(12);
      this.form.defensePerson=response3;
    },
    add()
    {
      adddefense(this.form).then(res=>{
        if(res.code==200)
        {
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.dialogFormVisible=false;
           local.reload();
          this.$refs.audioElement.play();
        }
      })
    },
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      let wsUrl = "ws:127.0.0.1:9111/websocket/1";
      this.websocket = new WebSocket(wsUrl);
      this.websocket.onopen = this.websocketonopen;
      this.websocket.onerror = this.websocketonerror;
      this.websocket.onmessage = this.setOnmessageMessage;
      this.websocket.onclose = this.websocketclose;
      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      // window.onbeforeunload = that.onbeforeunload
    },
    start() {
      console.log('start');
      console.log(this.$store.getters.name)
      //清除延时器
      this.timeoutObj && clearTimeout(this.timeoutObj);
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
      this.timeoutObj = setTimeout(() => {
        if (this.websocket && this.websocket.readyState == 1) {

          // let actions = {"邹局长":"收到马上派出警力抓捕"};
          this.websocket.send(JSON.stringify(actions));//发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
        } else {
          this.reconnect();
        }
        //定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
        this.serverTimeoutObj = setTimeout(() => {
          this.websocket.close();
        }, this.timeout)
      }, this.timeout)
    },
    reset() { // 重置心跳
      // 清除时间
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      // 重启心跳
      this.start();
    },
    // 重新连接
    reconnect() {
      if (this.lockReconnect) return
      this.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      this.timeoutnum && clearTimeout(this.timeoutnum);
      this.timeoutnum = setTimeout(() => {
        this.initWebSocket();
        this.lockReconnect = false;
      }, 5000)
    },
    async setOnmessageMessage(event) {
      // console.log(event.data, '获得消息');
      this.reset();
      // 自定义全局监听事件
      window.dispatchEvent(new CustomEvent('onmessageWS', {
        detail: {
          data: event.data
        }
      }))
      // 播放音频
      if (this.$refs.audioElement && this.$refs.audioElement.readyState >= 2) { // 确保音频已加载
        this.$refs.audioElement.play().catch(error => {
          console.error("播放音频失败:", error);
        });
      }
      // //发现消息进入    开始处理前端触发逻辑
      // if (event.data === 'success' || event.data === 'heartBath') return
    },
    websocketonopen() {
      //开启心跳
      this.start();
      console.log("WebSocket连接成功!!!"+new Date()+"----"+this.websocket.readyState);
      clearInterval(this.otimer);//停止
    },
    websocketonerror(e) {
      console.log("WebSocket连接发生错误" + e);
    },
    websocketclose(e) {
      this.websocket.close();
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      console.log("WebSocket连接关闭");
    },
    websocketsend(messsage) {
      that.websocket.send(messsage)
    },
    closeWebSocket() { // 关闭websocket
      that.websocket.close()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    getSocketData (res) {
      console.log(res.detail.data)
      // alert(res.detail.data)

    },

  },created() {
    // 可以在这里初始化 WebSocket 连接
    // this.initWebSocket('ws://your-websocket-url');
    this.getData();
    this.initWebSocket();
    window.addEventListener('onmessageWS', this.getSocketData)
  },

  beforeDestroy() {
    // 组件销毁前关闭 WebSocket 连接
    if (this.websocket) {
      this.websocket.close();
      clearTimeout(this.timeout);
      clearTimeout(this.timeoutObj);  // 清除心跳发送定时器
      clearTimeout(this.serverTimeoutObj); // 清除服务器响应超时定时器
    }
  },
};
</script>

<style scoped>
/* 样式可以根据需要添加 */
.card-container {
  display: flex;
  flex-wrap: wrap;
}
.card {
  border: 1px solid #eee;
  margin: 10px;
  padding: 10px;
  width: calc(25% - 20px); /* 根据需要调整卡片宽度 */
}
.card-header, .card-content, .card-footer {
  margin-bottom: 10px;
}
.card-info span {
  display: block;
  margin: 5px 0;
}
.card-info img {
  max-width: 100%; /* 确保图片不会超出其父容器 */
  height: auto; /* 保持图片的比例 */
}
</style>
